<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="margin-t">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="margin-t">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            :options="paramsList"
            v-model="paramsValue"
            :show-all-levels="false"
            :props="paramsProps"
            @change="getParamsKey"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick" class="margin-t">
        <!-- 动态参数 -->
        <el-tab-pane label="用户管理" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="btnDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <el-table class="margin-t" :data="manyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) of scope.row.attr_vals"
                  :key="item.id"
                  closable
                  @close="handleClose(scope.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editDialogShow(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数 -->
        <el-tab-pane label="配置管理" name="only">
          <!-- 展开行 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="btnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <el-table class="margin-t" :data="onlyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <pre>{{scope.row}}</pre>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editDialogShow(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetAddDialog"
    >
      <el-form
        :model="addParamsData"
        :rules="addParamsRules"
        ref="addParamsRuleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="value">
          <el-input v-model="addParamsData.value"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="resetDditDialog"
    >
      <el-form
        :model="editParamsData"
        :rules="editParamsRules"
        ref="editParamsRuleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="value">
          <el-input v-model="editParamsData.value"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "params",
  data() {
    return {
      paramsList: [], //商品分类数据
      paramsProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      paramsValue: [], //商品分类级联选择框选中数据
      activeName: "many", //当前标签页名称
      manyData: [], //动态参数数据列表
      onlyData: [], //静态参数数据列表
      addDialogVisible: false, //控制添加对话框
      addParamsData: {
        //添加参数的绑定数据
        value: ""
      },
      addParamsRules: {
        //添加参数表格检验规则
        value: [{ required: true, message: "请输入参数名称", trigger: "blur" }]
      },
      editDialogVisible: false, //控制修改参数对话框
      editParamsData: {
        //修改参数的绑定数据
        value: "",
        attr_id: "",
        id: ""
      },
      editParamsRules: {
        //修改参数表格检验规则
        value: [{ required: true, message: "请输入参数名称", trigger: "blur" }]
      }
    };
  },
  methods: {
    async getParams() {
      //获取商品分类数据列表
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status === 200) {
        this.paramsList = res.data;
      } else {
        this.$message.error("获取数据失败");
      }
    },
    getParamsKey() {
      //商品分类选择器发生变化触发
      if (this.paramsValue.length !== 3) {
        //如果选择器长度不等于三，清空选中数据
        return (this.paramsValue = []);
      }
      this.getParamsData();
    },
    handleClick() {
      //标签页切换发生变化
      console.log(this.attrId);
      this.getParamsData();
    },
    async getParamsData() {
      //请求表格参数数据
      if (this.paramsValue.length === 3) {
        const { data: res } = await this.$axios.get(
          `categories/${this.attrId}/attributes`,
          {
            params: {
              sel: this.activeName
            }
          }
        );
        //分割attr_vals
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(" ") : []; //判断attr_vals是否为空
          //为每一个数据都提供自己的value
          item.inputVisible = false; //控制隐藏与显示
          item.inputValue = ""; //控制输入框
        });

        if (res.meta.status === 200) {
          if (this.activeName === "many") {
            //动态参数数据
            this.manyData = res.data;
          } else {
            this.onlyData = res.data;
          }
        } else {
          this.$message.error("获取数据失败");
        }
      }
    },
    addParams() {
      //添加参数
      this.$refs.addParamsRuleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.post(
            `categories/${this.attrId}/attributes`,
            {
              attr_name: this.addParamsData.value,
              attr_sel: this.activeName
            }
          );
          if (res.meta.status === 201) {
            this.$message.success("添加参数成功");
            this.addDialogVisible = false;
            this.getParamsData();
          } else {
            this.$message.error("添加参数失败");
          }
        } else {
          return;
        }
      });
    },
    resetAddDialog() {
      //关闭添加对话框重置表单
      this.$refs.addParamsRuleForm.resetFields();
    },
    resetDditDialog() {
      //关闭修改对话框重置表单
      this.$refs.editParamsRuleForm.resetFields();
    },
    editParams() {
      //修改参数确认按钮
      this.$refs.editParamsRuleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.put(
            `categories/${this.attrId}/attributes/${this.editParamsData.attr_id}`,
            {
              attr_name: this.editParamsData.value,
              attr_sel: this.activeName
            }
          );
          if (res.meta.status === 200) {
            this.$message.success("参数修改成功");
            this.editDialogVisible = false;
            this.getParamsData();
          }
        } else {
          return;
        }
      });
    },
    editDialogShow(row) {
      //修改参数按钮
      // console.log(row);
      this.editDialogVisible = true;
      this.editParamsData.value = row.attr_name; //传过来的属性赋值给输入框
      this.editParamsData.attr_id = row.attr_id;
    },
    async removeParmas(row) {
      //删除分类属性
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(res);
      if (res === "confirm") {
        const { data: res } = await this.$axios.delete(
          `categories/${this.attrId}/attributes/${row.attr_id}`
        );
        if (res.meta.status === 200) {
          this.$message.success("删除成功");
          this.getParamsData();
        }
      } else {
        this.$message.error("取消删除");
      }
    },
    async handleInputConfirm(row) {
      //键盘按下和失去焦点触发事件,添加标签
      if (row.inputValue.trim().length === 0) {
        //判断输入是否包含空格
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue);
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrValus(row);
    },
    async saveAttrValus(row) {
      //发起请求保存操作，标签删除与添加
      const { data: res } = await this.$axios.put(
        `categories/${this.attrId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status === 200) {
        this.$message.success("更新参数成功");
      } else {
        this.$message.error("更新参数失败");
      }
    },
    showInput(row) {
      //显示动态添加参数输入框
      row.inputVisible = true;
      //显示输出框时获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleClose(row, i) {
      //移除参数标签
      console.log(row);
      row.attr_vals.splice(i, 1);
      this.saveAttrValus(row);
    }
  },
  computed: {
    btnDisabled() {
      //判断选择框是否选中，选中则可以点击按钮
      if (this.paramsValue.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    attrId() {
      //获取商品分类id
      if (this.paramsValue.length === 3) {
        return this.paramsValue[this.paramsValue.length - 1];
      } else {
        return null;
      }
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  },
  created() {
    this.getParams();
  }
};
</script>

<style scoped>
.margin-t {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>